Import cal3d
Import minib3d

Class CalImage

	Field w:Int,h:Int
	Field pixels:String[]
	Field tex:TPixmap
	Field texture:TTexture
	Field pos:Int,posx:Int,posy:Int
	Field filename:String
	Field name:String
	Field finished:Bool
	
	Method New()
		w = 0
		h = 0
		pos = 0
		pixels = New String[0]
		finished = False
		posx = 0
		posy = 0
	End
	
	Method New(ww:Int,hh:Int,pix:String[])
		w = ww
		h = hh
		pixels = pix
		finished = False
		posx = 0
		posy = 0
		Print "New CalImage W: "+w+" H: "+h+" pixels: "+pixels.Length
		tex = TPixmap.CreatePixmap(w,h)
		
				
	End
	
	Method MakeTexture:TTexture()
		Print "Create Texture"
		texture = TTexture.CreateTexture(w,h)
		texture.pixmap = tex
		Return texture
	End
	
	Method IsFinished:Bool()
		Return finished
	End
	
	Method Update:Void()
		
		If finished = False Then
			
			For Local i:Int = 0 To 255
				If pos < pixels.Length Then
					Local col:Int[] = IntToRGBA(Int(pixels[pos]))
					#If( TARGET = "flash" )
						tex.SetPixel(posx, posy,col[1],col[2],col[3],255)'col[0])
					#Else
						tex.SetPixel(posx, posy,col[1],col[2],col[3],col[0])
					#Endif
					'Print "Put Pixel: "+posx+" "+posy
					posx = posx + 1
					If posx >= w Then
						posx = 0
						posy = posy+1
						'Print "posy: "+posy
					Endif
					pos = pos + 1
					
				Else
					Print "Finished Loading Image"
					MakeTexture()
					finished = True
					Exit
				Endif
			Next
		Endif
	
	End
	
	
	
	

End

Function IntToRGBA:Int[]( Value:Int)
	Local rgba:Int[4]
	rgba[0] = ( Value Shr 24 ) & $FF
	rgba[1] = ( Value Shr 16) & $FF
	rgba[2] = ( Value Shr 8) & $FF
	rgba[3] = Value & $FF
	Return rgba
End Function

Function RGBAtoInt:Int( red:Byte, Green:Byte, Blue:Byte, Alpha:Byte )
	Return ( alpha Shl 24 | red Shl 16 | green Shl 8 | blue )
End Function